/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Models;

import JDBC.UtilsJDBC;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author escabia
 */
public class Models {
    private ArrayList<Model> models;
    
    /**
     * Constructor de la clase
     */
    public Models(){
        this.models = new ArrayList<>();
        UtilsJDBC selectModels = new UtilsJDBC(); 
        this.models = selectModels.getModels();
        selectModels.disconnect();
    }
    
    
    
    /**
     * Añade un modelo a modelos
     * Return errores que se han producido
     * @param path ruta del archivo
     * @return errores
     * @throws java.io.IOException
     */
    public ArrayList<String> addModel(String path) throws IOException{
        ArrayList<String> errors = new ArrayList<>();//Se podría hacer otra clase con los errores.....
        UtilsJDBC inserts = new UtilsJDBC(); 
        
        /** Se lee el fichero SCRIPT de entrada */
        FileReader fr = null;
        try {
            fr = new FileReader(path);
            BufferedReader entrada = new BufferedReader(fr);
            String cadena = entrada.readLine();
            while (cadena != null) {
                if(cadena.startsWith("INSERT") || cadena.startsWith("COMMIT")){
                    inserts.insert(cadena.substring(0, cadena.length()-1));//Hay que descomentar el insert para insertar correctamente
                    System.out.println(cadena.substring(0, cadena.length()-1));
                }
                cadena = entrada.readLine();
            }
            models.add(inserts.getLastModel());
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        
        inserts.disconnect();//desconecta
        return errors;
    }
    
    /**
     * Modelos creados
     * @return modelos existentes
     */
    public ArrayList<Model> getModels(){
        return this.models;
    }
}
